# from litestar.repository import AbstractAsyncRepository, FilterTypes, LimitOffset
from advanced_alchemy.filters import (
    FilterTypes,
    LimitOffset,
    )
from typing import Any
from sqlalchemy import select, and_
from models.test1 import Test1Model
from sqlalchemy.ext.asyncio import AsyncSession

__all__ = ["Service"]

class Service:
    model_type: type[Test1Model] = Test1Model
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def create(self, data: Test1Model) -> Test1Model:
        async with self.session.begin():
            self.session.add(data)
            await self.session.flush()
            await self.session.refresh(data)
        return data
    
    async def detail(self, id_: Any) -> Test1Model:
        return self.session.get(self.model_type,id_)
    
    async def list(self, *filters: FilterTypes, **kwargs: Any) -> list[Test1Model]:
        query = select(self.model_type)
        for filter in filters:
            if isinstance(filter, LimitOffset):
                query.limit(filter.limit).offset(filter.offset)
        res = await self.session.execute(query)
        return res.scalars().all

    async def update(self, id_: Any, updated_data: Test1Model) -> Test1Model:
        test1 = await self.session.get(self.model_type, id_)
        
        # 检查是否找到了该记录
        if test1 is not None:
            # 遍历传入的新数据字典，并更新原有记录的属性
            for attr_name, attr_value in updated_data.to_dict().items():
                setattr(test1, attr_name, attr_value)

            # 应该添加原始对象（test1）而不是传入的新数据（data）到会话以进行更新
            self.session.add(test1)

            # 提交事务以保存更改
            await self.session.commit()

            # 刷新已提交的对象以获取最新的数据库值（如果有必要）
            await self.session.refresh(test1)

            return test1
        else:
            raise ValueError(f"Record with id={id_} not found.")
